<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="pdepartmenting-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyWord" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="Serch">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="名称" width="120" sortable>
			</el-table-column>
			<el-table-column prop="sn" label="编码" width="120" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="100" sortable>
				<template scope="scope">
					<span style="color: green" v-if="scope.row.state === 0">启用</span>
					<span style="color: red" v-else-if="scope.row.state === -1">禁用</span>
					<span v-else>未知</span>
				</template>
			</el-table-column>
			<el-table-column prop="manager.username" label="管理员" width="100" sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="父级部门" sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next"
						   @current-change="handleCurrentChange"
						   :page-size="pageSize"
						   :current-page="currentPage"
						   :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增/修改界面-->
		<el-dialog :title="title" :visible.sync="departmentFormVisible" :close-on-click-modal="false">
			<el-form :model="departmentForm" label-width="80px" :rules="departmentFormRules" ref="departmentForm">
				<el-form-item label="名称" prop="name">
					<el-input v-model="departmentForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="编码" prop="sn">
					<el-input v-model="departmentForm.sn" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="departmentForm.state">
						<el-radio class="radio" :label="0">启用</el-radio>
						<el-radio class="radio" :label="-1">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="管理员" prop="manager">
					<!--<el-input v-model="departmentForm.manager" auto-complete="off"></el-input>-->
					<el-select v-model="departmentForm.manager" value-key="id" placeholder="请选择">
						<el-option
								v-for="item in employees"
								:key="item.id"
								:label="item.username"
								:value="item">
							<spanpethome style="float: left">{{ item.username }}</spanpethome>
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
						</el-option>
					</el-select>
				</el-form-item>
				<!-- 绑定模型  从下面取值
				:options="deptTree" 取值来源
				label:'name', 匹配值
				value:'id'   匹配值
				-->
				<el-form-item label="上级部门" prop="parent">
					<el-cascader v-model="departmentForm.parent"
							:options="deptTree"
							:props="{ checkStrictly: true,
								label:'name',
							 	value:'id'}"
							clearable></el-cascader>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="departmentFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="departmentSubmit" :loading="departmentLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, departmentDepartment } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
					keyWord: ''
				},
				departments: [],
				employees:[],//员工数据
				deptTree:[],//部门树
				total: 0,
                pageSize:10,
                currentPage: 1,
                listLoading: false,
				sels: [],//列表选中列

				departmentFormVisible: false,//新增、修改界面是否显示
				departmentLoading: false,//等待框
				departmentFormRules: {//数据校验
					name: [
						{ required: true, message: '请输入名称', trigger: 'blur' }
					],
                    sn: [
                        { required: true, message: '请输入编码', trigger: 'blur' }
                    ]
				},
				//新增修改界面数据
				departmentForm: {
				    id:null,
					name: '',
					sn:  '',
					state: 0,
                    manager: null,
                    parent: null
				}

			}
		},
		methods: {
            Serch(){
                this.currentPage = 1;
                this.getDepartments();

			},
			//获取最新当前页数，刷新页面
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDepartments();
			},
			//获取部门列表
			getDepartments() {
				let para = {
				    //将我获得的当前页数  以及显示条数获取并重新赋值
					//高级查询的名字 queery内记得添加字段 跟着分页的数据一起传递
					//上面将高级查询的name 改为了keyword  下面这里重新复制也要改
                    currentPage: this.currentPage,
					pageSize: this.pageSize,
                    keyWord: this.filters.keyWord

				};
				this.listLoading = false;
				//NProgress.start();
				// getDepartmentListPage(para).then((res) => {
				// 	this.total = res.data.total;
				// 	this.departments = res.data.departments;
				// 	this.listLoading = false;
				// 	//NProgress.done();
				// });
				this.$http.post("/department",para)
					.then(result=>{
						//取出对象中对应的数据
                        this.total = result.data.total;
                        this.departments = result.data.rows;
                        //每次成功加载关闭忙等
                        this.listLoading = false;
					})
			},
			//获取管理员数据
            getEmployees() {
                this.$http.get("/employee")
                    .then(result=>{
                        //取出对象中对应的数据
                        result = result.data;
                        this.employees = result;
                        //每次成功加载关闭忙等
                        this.listLoading = false;
                    }).catch(result=>{
						this.$message({
							message: "查询管理员失败",
							type: 'error'
						})
				})
            },
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.$http.delete("/department/"+row.id)
						.then(result=>{
						    //关闭忙等
                            this.listLoading = false;
                            //后端返回ajax对象
                            result = result.data;
                            if(result.success){
                                this.$message({
									message: result.msg,
									type: 'success'
								})
							}else {
                                this.$message({
                                    message: result.msg,
                                    type: 'error'
                                });
                            };
							//定位到第一页
							this.currentPage = 1;
							//刷新页面
							this.getDepartments();
						})
						.catch(result=>{
						    //如果删除失败  打印一下错误原因
							console.log(result);
							this.$message({
								message: "删除失败",
								type: 'error'
							})
						})

				}).catch(() => {//点击取消就不管了

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
			    this.title = "修改";
				this.departmentFormVisible = true;//弹出模态框   上面为false 重新赋值就打开
				this.departmentForm = Object.assign({}, row);//克隆表格数据 回显
				this.getdeptTree();
				//首先 row里面已有dir数据  可以取出来   回显部门
				let dirPath = row.dirPath;
				if(dirPath){
				    //如果不为空才整分割
					let array = dirPath.split("/");//["","1","5","8"]
					//封装一个数组
					let parent = [];
					//循环取出  不要最后一位，因为最后一位是自己的
					for(let i = 1;i<array.length-1;i++){
					    //循环装入
                        parent.push(parseInt(array[i]));
					}
					//测试一下
					console.log(parent);
                    this.departmentForm.parent = parent; //回显部门的数组
                }
			},
			//显示新增界面
			handleAdd: function () {
                this.title = "新增";
				this.departmentFormVisible = true;//弹出模态框
				this.departmentForm = {//清空表格数据
                    id:null,
                    name: '',
                    sn:  '',
                    state: 0,
                    manager: null,
                    parent: null
				};
                this.getdeptTree();
			},
			//新增修改方法
			departmentSubmit: function () {
			    //validate失去焦点校验表格数据  无异常才能提交
				this.$refs.departmentForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.departmentLoading = true;//按钮忙等开启
							//将表格的数据赋值给department
							let department = Object.assign({}, this.departmentForm);
                            //处理后端需要的数据格式
							if(department.parent){
							    //加入我的对象 parent有值  取出重新赋值给parent
                                let parent =department.parent;
                                department.parent = {"id":parent[parent.length-1]};
                            }

							//发送请求
							this.$http.put("/department",department).
							then(result=>{
                                this.departmentLoading = false;//按钮忙等关闭
                                result = result.data;
                                if(result.success){
                                    this.$message({
                                        message: result.msg,
                                        type: 'success'
                                    })
								}else {
                                    this.$message({
                                        message: result.msg,
                                        type: 'error'
                                    });
								}
                                this.departmentFormVisible = false;//关闭模态框
                                this.getDepartments();//重新查询
							})
							.catch(result=>{
                                this.$message({
                                    message: "操作失败",
                                    type: 'error'
                                });
                            })
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
			    //将当前点击获得的id装入数组
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
                    this.listLoading = true;
                    this.$http.patch("/department",ids)
                        .then(result=>{
                            //关闭忙等框
                            this.listLoading = false;
                            //后端返回ajax对象
                            result = result.data;
                            if(result.success){
                                this.$message({
                                    message: result.msg,
                                    type: 'success'
                                })
                            }else {
                                this.$message({
                                    message: result.msg,
                                    type: 'error'
                                });
							};
                            //定位到第一页
                            this.currentPage = 1;
                            //刷新页面
                            this.getDepartments();
                        })
                        .catch(result=>{
                            //如果删除失败  打印一下错误原因
                            this.$message({
                                message: "删除失败",
                                type: 'error'
                            })
                        })
				})
					.catch(() => {//这是点击取消

				});
			},
            //获取部门树
            getdeptTree() {
                this.$http.get("/department/tree")
                    .then(result=>{
                        //取出对象中对应的数据
                        result = result.data;
                        this.deptTree = result;
                        //每次成功加载关闭忙等
                        this.listLoading = false;
                    }).catch(result=>{
                    this.$message({
                        message: "查询部门树失败",
                        type: 'error'
                    })
                })
            }
		},
		mounted() {
			this.getDepartments();
            this.getEmployees();
		}
	}

</script>

<style scoped>

</style>